package cn.qing.controller;

import cn.qing.pojo.Permission;
import cn.qing.pojo.Role;
import cn.qing.service.RoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import sun.awt.SunHints;

import java.util.List;

@Controller
@RequestMapping("role")
public class RoleController {

    @Autowired
    RoleService roleService;

    @RequestMapping("findAll")
    public ModelAndView findAll(
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "size",defaultValue = "5") Integer size){
        ModelAndView mv = new ModelAndView();
        List<Role> roleList = roleService.findAll(page,size);
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);
        mv.addObject("pageInfo",pageInfo);
        mv.setViewName("role-list");
        return mv;
    }

    /**
     * 角色的添加
     * @param role
     * @return
     */
    @RequestMapping("save")
    public String save(Role role){

        roleService.save(role);
        return "redirect:findAll.do";
    }

    /**
     * 用户详情
     */
    @RequestMapping("findById")
    public ModelAndView findById(@RequestParam("id") Integer id){
        ModelAndView mv = new ModelAndView();
        Role role = roleService.findById(id);

        mv.addObject("role",role);
        mv.setViewName("role-show");
        return mv;
    }

    /**
     * 给角色添加权限
     * @param id
     * @return
     */
    @RequestMapping("findRoleByIdAndAllPermission")
    public ModelAndView findRoleByIdAndAllPermission(Integer id){

        //获取roleId
        Role rolebyId = roleService.findById(id);
        //获取角色没有的权限
        List<Permission> permissionList = roleService.findOtherPermission(id);

        ModelAndView mv = new ModelAndView();
        mv.addObject("role",rolebyId);
        mv.addObject("permissionList",permissionList);
        mv.setViewName("role-permission-add");
        return mv;
    }

    /**
     * 为添加权限
     * @param roleId
     * @param ids
     * @return
     */
    @RequestMapping("addPermissionToRole")
    public String addPermissionToRole(Integer roleId,Integer[] ids){
        roleService.addPermissionToRole(roleId,ids);
        return "redirect:findAll.do";
    }
}
